<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <div class="layui-input-inline" style="width: 70px">
                                        <select id="timeType" lay-filter="timeType">
                                            <option value="year">年</option>
                                            <option value="month" selected>月</option>
                                            <option value="date">日</option>
                                        </select>
                                    </div>
                                    <div class="layui-input-inline" id="inputTimeBox">
                                        <input type="hidden" class="layui-input" readonly id="inputTimeYear"
                                               placeholder="请选择年份">
                                        <input type="text" class="layui-input" readonly id="inputTimeMonth"
                                               placeholder="请选择月份">
                                        <input type="hidden" class="layui-input" readonly id="inputTimeDate"
                                               placeholder="请选择天">

                                        <input type="hidden" name="startCreateTime">
                                        <input type="hidden" name="endCreateTime">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">仓库：</label>
                                    <div class="layui-input-inline">
                                        <select name="warehouseId" lay-filter="warehouseId" class="common-select-search"></select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">物料编号：</label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" placeholder="请输入物料编号" name="skuCode">
                                    </div>
                                </div>

                                <div class="layui-inline">
                                    <label class="layui-form-label">物料名称：</label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" placeholder="请输入物料名称" name="skuName">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">规格码：</label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" placeholder="请输入规格码" name="oldSpecCode">
                                    </div>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button class="layui-btn color-green" lay-filter="formSubSearchLog" lay-submit
                                            layui-form-keyDownSearch="true">查询
                                    </button>
                                    <button class="layui-btn color-white" lay-filter="resets" lay-submit>重置
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows" style="padding-top: 15px;">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="toolCabinetTableExport" class="layui-btn color-green"
                                    lay-filter="toolCabinetTableExport" lay-submit>导出
                            </button>
                        </div>
                        <div class="lay-btn-rt">
                        </div>
                    </div>
                </div>
            </div>
            <!-- 接入称重柜表格 -->
            <table class="layui-table" id="toolCabinetTable" lay-filter="toolCabinetTable"></table>
        </div>
    </div>
</div>
<style>
    #toolCabinetTable + div .layui-table-cell {
        padding: 0 5px;
    }

    #inputTimeBox input {
        text-align: center;
    }

    #inputTimeBox input::placeholder {
        text-align: left;
    }
</style>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin', 'laydate'], function () {
        let $ = layui.jquery;
        let {layer, form, table, config, admin, upload, laydate} = layui;
        let currentDate = new Date();
        let currentYear = currentDate.getFullYear(),
            currentMonth = (currentDate.getMonth() + 1) > 9 ? (currentDate.getMonth() + 1) : '0' + (currentDate.getMonth() + 1),
            currentDay = currentDate.getDate() > 9 ? currentDate.getDate() : '0' + currentDate.getDate();
        let timeSlotStart = currentYear + '-' + currentMonth + '-01 00:00:00',
            timeSlotEnd = currentYear + '-' + currentMonth + '-' + getMonthDays(currentYear, currentMonth) + ' 23:59:59';

        $("#inputTimeBox input[name='startCreateTime']").val(timeSlotStart);
        $("#inputTimeBox input[name='endCreateTime']").val(timeSlotEnd);

        admin.selectSearch();

        // 获取仓库
        admin.req('enterprisecab/warehouse/admin/warehouse/list', {limit: 9999}, function (res) {
            if (200 == res.code) {
                loadSelectHtmlNew(res.data,'所有仓库','warehouseId','.lay-header',1)
               /* var optionHtml = '<option value="">请选择仓库</option>';
                for (var k = 0; k < res.data.length; k++) {
                    optionHtml += '<option value="' + res.data[k].id + '">' + res.data[k].name + '</option>';
                }
                $("select[name='warehouseId']").html(optionHtml);
                form.render('select');*/
            } else {
                loadSelectHtmlNew([],'所有仓库','warehouseId','.lay-header',1)
                // layer.msg('获取仓库失败', {icon: 2, time: 1000});
            }
        }, 'GET');

        form.on('select(warehouseId)',function(data){
            // $(data.elem).parents('.layui-form').find('[layui-form-keyDownSearch="true"]').click();
        });

        // 初始化时间选择器
        let inputTimeYear = laydate.render({
            elem: '#inputTimeYear',
            type: 'year',
            format: 'yyyy',
            range: '至',
            done: function (value, date, endDate) {
                if (value) {
                    let timeArray = value.split("至");
                    $("#inputTimeBox input[name='startCreateTime']").val(timeArray[0].trim() + '-01-01 00:00:00');
                    $("#inputTimeBox input[name='endCreateTime']").val(timeArray[1].trim() + '-12-31 23:59:59');
                    $(this.elem).parents('.layui-form').find('[layui-form-keyDownSearch="true"]').click();
                } else {
                    timing(this.type)
                }
            }
        });
        let inputTimeMonth = laydate.render({
            elem: '#inputTimeMonth',
            type: 'month',
            value: (currentYear + '-' + currentMonth) + ' 至 ' + (currentYear + '-' + currentMonth),
            range: '至',
            done: function (value, date, endDate) {
                if (value) {
                    let timeArray = value.split("至");
                    $("#inputTimeBox input[name='startCreateTime']").val(timeArray[0].trim() + '-01 00:00:00');
                    $("#inputTimeBox input[name='endCreateTime']").val(timeArray[1].trim() + '-' + getMonthDays(endDate.year, endDate.month) + ' 23:59:59');
                    $(this.elem).parents('.layui-form').find('[layui-form-keyDownSearch="true"]').click();
                } else {
                    timing(this.type)
                }
            }
        });
        let inputTimeDate = laydate.render({
            elem: '#inputTimeDate',
            type: 'date',
            format: 'yyyy-MM-dd',
            range: '至',
            done: function (value, date, endDate) {
                if (value) {
                    let timeArray = value.split("至");
                    $("#inputTimeBox input[name='startCreateTime']").val(timeArray[0].trim() + ' 00:00:00');
                    $("#inputTimeBox input[name='endCreateTime']").val(timeArray[1].trim() + ' 23:59:59');
                    $(this.elem).parents('.layui-form').find('[layui-form-keyDownSearch="true"]').click();
                } else {
                    timing(this.type)
                }
            }
        });

        //年月日选择操作
        form.on('select(timeType)', function (data) {
            timing(data.value);
        });

        // 更换年月日选择器
        function timing(data) {
            $('#inputTimeBox > input').val('');
            $('#inputTimeBox > input').attr('type', 'hidden');
            if (data === 'year') {
                $('#inputTimeYear').attr('type', 'text');
                $('#inputTimeYear').val((currentYear) + ' 至 ' + (currentYear));
                $('input[name="startCreateTime"]').val(currentYear + '-01-01 00:00:00');
                $('input[name="endCreateTime"]').val(currentYear + '-12-31 23:59:59');

            } else if (data === 'month') {
                $('#inputTimeMonth').attr('type', 'text');
                $('#inputTimeMonth').val((currentYear + '-' + currentMonth) + ' 至 ' + (currentYear + '-' + currentMonth));
                $('input[name="startCreateTime"]').val(currentYear + '-' + currentMonth + '-01 00:00:00');
                $('input[name="endCreateTime"]').val(currentYear + '-' + currentMonth + '-' + getMonthDays(currentYear, currentMonth) + ' 23:59:59');

            } else if (data === 'date') {
                $('#inputTimeDate').attr('type', 'text');
                $('#inputTimeDate').val((currentYear + '-' + currentMonth + '-' + currentDay) + ' 至 ' + (currentYear + '-' + currentMonth + '-' + currentDay));
                $('input[name="startCreateTime"]').val(currentYear + '-' + currentMonth + '-' + currentDay + ' 00:00:00');
                $('input[name="endCreateTime"]').val(currentYear + '-' + currentMonth + '-' + currentDay + ' 23:59:59');
            }
            form.render();
            $('[layui-form-keyDownSearch="true"]').click();
        }

        //  渲染接入称重柜表格
        let insTb = table.render({
            elem: '#toolCabinetTable',
            title: '物料库存统计表',
            url: config.base + 'enterprisecab/order/admin/materialInventoryStatisticsReport/list',
            where: {startCreateTime: timeSlotStart, endCreateTime: timeSlotEnd},
            page: true,
            cols: [
                [
                    {type: "numbers", title: "序号", rowspan: 2, align: "center"},
                    {field: "skuCode", title: "物料编号", rowspan: 2, align: "center", sort: true},
                    {field: "skuName", title: "物料名称", rowspan: 2, align: "center"},
                    {field: "oldSpecCode", title: "规格码", rowspan: 2, align: "center"},
                    {field: "brandName", title: "品牌", rowspan: 2, align: "center"},
                    {field: "", title: "期初", colspan: 2, align: "center"},
                    {field: "", title: "入库", colspan: 2, align: "center"},
                    {field: "", title: "出库", colspan: 2, align: "center"},
                    {field: "", title: "结存", colspan: 2, align: "center"},
                ],
                [
                    {field: 'openingPackQuantity', title: "期初数量(包装计)", align: "center", width: 135},
                    {field: 'openingQuantity', title: "期初数量(基础单位计)", align: "center", width: 165},
                    {field: 'storagePackQuantity', title: "入库数量(包装计)", align: "center", width: 135},
                    {field: 'storageQuantity', title: "入库数量(基础单位计)", align: "center", width: 165},
                    {field: 'outboundPackQuantity', title: "出库数量(包装计)", align: "center", width: 135},
                    {field: 'outboundQuantity', title: "出库数量(基础单位计)", align: "center", width: 165},
                    {field: 'balancePackQuantity', title: "结存数量(包装计)", align: "center", width: 135},
                    {field: 'balanceQuantity', title: "结存数量(基础单位计)", align: "center", width: 165},
                ]
            ],
            done: function (res, curr, count) {
            }
        });
        form.render('select');

        // 工具条点击事件
        table.on('tool(toolCabinetTable)', function (obj) {
            let data = obj.data;
            if (obj.event === 'details') {
            }
        });

        //监听排序
        table.on('sort(toolCabinetTable)', function (obj) {
            table.reload('toolCabinetTable', {initSort: obj, where: {sort: obj.field, order: obj.type}});
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
            return false;
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            $(".lay-header").find('select').val("");
            $(".lay-header").find('input').val("");
            let field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            $(".lay-header").find('select[lay-filter="timeType"]').val("month");
            timing('month');
            field.startCreateTime = timeSlotStart;
            field.endCreateTime = timeSlotEnd;
            insTb.reload({where: field, page: {curr: 1}}, 'data');
            return false;
        });


        // 获取月份的天数
        function getMonthDays(year, month) {
            let targetDate = new Date(year, month, 0); // 目标月份的最后一天
            let totalDays = targetDate.getDate(); // 获取目标月份的天数
            return totalDays;
        }

        // 导出
        form.on('submit(toolCabinetTableExport)', function (d) {
            /*layer.load(2);
            d.field.limit = 999999;
            admin.req('enterprisecab/order/admin/materialInventoryStatisticsReport/list', d.field, res => {
                layer.closeAll('loading');
                if (res.code === 200) {
                    table.exportFile(insTb.config.id, res.data, 'xls', insTb.config.title);
                }
            });*/
            let startCreateTime = d.field.startCreateTime;
            let endCreateTime = d.field.endCreateTime;
            let warehouseId = d.field.warehouseId;
            location.href = config.base + 'enterprisecab/order/admin/materialInventoryStatisticsReport/export?startCreateTime=' + startCreateTime + "&endCreateTime=" + endCreateTime + "&warehouseId=" + warehouseId;
        });

        function loadSelectHtmlNew(data, tips, htmltarget, formName, type) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                $(formName + " select[name='" + htmltarget + "']").html(html);
                form.render('select');
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type == 1) {
                    html += `<option value='${data[i].id}'>${data[i].name}</option>`;
                } else if (type == 2) {
                    html += `<option value='${data[i].id}'>${data[i].nickname}</option>`;
                }
            }
            $(formName + " select[name='" + htmltarget + "']").html(html);
            form.render('select');
        }
    });
</script>